package com.freewater.library.catalogue.infrastructure.po;

import com.freewater.library.catalogue.infrastructure.model.BookImpl;
import com.freewater.library.catalogue.model.Book;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.time.LocalDate;

@Table(name = "book",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = {"isbn"})
        })
@Entity
@Data
@NoArgsConstructor
public class BookPo {
    /**
     * 主键ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    /**
     * ISBN
     */
    private String isbn;
    /**
     * 标题
     */
    private String title;
    /**
     * 副标题
     */
    private String subtitle;
    /**
     * 作者
     */
    private String author;
    /**
     * 出版社
     */
    private String publishingHouse;
    /**
     * 出版日期
     */
    private LocalDate publicationDate;
    /**
     * 封面图
     */
    private String cover;
    /**
     * 定价
     */
    private BigDecimal listPrice;
    /**
     * 页数
     */
    private Integer pageCount;
    /**
     * 装帧
     */
    private String bindingAndLayout;
    /**
     * 丛书
     */
    private String series;
    /**
     * 介绍/描述
     */
    private String description;
    /**
     * 乐观锁版本
     */
    private int version;

    public BookPo(Book book) {
        this.isbn = book.getIsbn();
        this.title = book.getTitle();
        this.subtitle = book.getSubtitle();
        this.author = book.getAuthor();
        this.publishingHouse = book.getPublishingHouse();
        this.publicationDate = book.getPublicationDate();
        this.cover = book.getCover();
        this.listPrice = book.getListPrice();
        this.pageCount = book.getPageCount();
        this.bindingAndLayout = book.getBindingAndLayout();
        this.series = book.getSeries();
        this.description = book.getDescription();
        if (book instanceof BookImpl bookImpl) {
            this.id = bookImpl.getDbId();
            this.version = bookImpl.getVersion();
        } else {
            this.version = 0;
        }
    }

    public static Book convert(BookPo record) {
        BookImpl book = new BookImpl(record.getIsbn(),
                record.getTitle(),
                record.getSubtitle(),
                record.getAuthor(),
                record.getPublishingHouse(),
                record.getPublicationDate(),
                record.getCover(),
                record.getListPrice(),
                record.getPageCount(),
                record.getBindingAndLayout(),
                record.getSeries(),
                record.getDescription());
        book.setDbId(record.getId());
        book.setVersion(record.getVersion());
        return book;
    }
}
